package com.bert.controller;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Properties;

@RequestMapping("/nacos")
@RestController
public class NacosController {

    @Value("${spring.cloud.nacos.discovery.serverAddr}")
    private String discoveryServerAddr;
    @Value("${spring.cloud.nacos.discovery.namespace}")
    private String discoveryNamespace;
    @Value("${spring.cloud.nacos.discovery.group}")
    private String discoveryGroup;

    @GetMapping("/getAll")
    public List<Instance> getAll(String serviceName) throws NacosException {
        NamingService naming = getService();
        return naming.getAllInstances(serviceName);
    }

    @GetMapping("/login")
    public Boolean login(String serviceName, String ip, int port, String clusterName){
        NamingService naming = getService();
        boolean resulet = true;
        try {
            naming.registerInstance(serviceName, ip, port, clusterName);
        } catch (NacosException e) {
            resulet = false;
            throw new RuntimeException(e);
        }
        return resulet;
    }

    @GetMapping("/logout")
    public Boolean logout(String serviceName, String ip, int port, String clusterName){
        NamingService naming = getService();
        boolean resulet = true;
        try {
            naming.deregisterInstance(serviceName, ip, port, clusterName);
        } catch (NacosException e) {
            resulet = false;
            throw new RuntimeException(e);
        }
        return resulet;
    }



    @SneakyThrows
    private NamingService getService(){
        Properties properties = new Properties();
        properties.put("serverAddr", discoveryServerAddr);
        properties.put("namespace", discoveryNamespace);
        properties.put("group", discoveryGroup);
        return NamingFactory.createNamingService(properties);
    }


}
